//
//  DataEngine.m
//  MobileOA
//
//  Created by chenxiaojuan on 13-4-16.
//  Copyright (c) 2013年 chenxiaojuan. All rights reserved.
//

#import "DataEngine.h"
#import "UIDevice+IdentifierAddition.h"
#import <sys/utsname.h>
#import "ContactDao.h"
#import "MessageSessionDao.h"
#import "MessageSession.h"
#import "PublicAccount.h"
#import "KeyWordDao.h"
#import "PublicAccountDao.h"
#import "WeatherData.h"
#import "DataDictDao.h"
#import <BaiduMapAPI/BMapKit.h>

@interface DataEngine () <BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>
{
    ServerEngine* _serverEngine;
    MsgEngine* _msgEngine;
    NSString* _appId;
    id<DEDelegate> _delegate;
    NSString* _userId;
    NSString* _userPassword;
    BOOL _isLoaded;
    NSDictionary* _msgTypeToTitle;
    NSString* _msgBroadcastName;
    NSString* _deviceToken;
    
    
    NSString* _fileEngineeUrl;
    BMKMapManager * mapManager;
    BMKLocationService * _locService;
    BMKGeoCodeSearch * _geocodesearch;


}

@property(nonatomic,readonly)ServerEngine* serverEngine;
@property(nonatomic,readonly)MsgEngine* msgEngine;
@property(nonatomic,readonly)NSMutableArray* receiptMsgList;

@end



@implementation DataEngine

@synthesize msgTypeToTitle = _msgTypeToTitle;
@synthesize msgBroadcastName = _msgBroadcastName;

@synthesize deviceToken= _deviceToken;

@synthesize fileEngineeUrl= _fileEngineeUrl;


+(DataEngine*)getInstance
{
    static DataEngine* _de = nil;
    if ( !_de )
    {
        _de = [[DataEngine alloc] init];
    }
    return _de;
}

-(id)init
{
    if ( self = [super init] )
    {
        _isLoaded = NO;
    }
    //
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealWeatherChangeNotifier:) name:WEATHER_REFRESH_BROADCAST object:nil];
    
    return self;
}

-(void)dealWeatherChangeNotifier:(NSNotification*)notification
{
    NSLog(@"接收重新定位消息");
    [_locService startUserLocationService];
}


-(void)reload
{
    [self checkin];
}

-(void)unload
{
    [self.msgEngine disconnect];
}

-(void)checkin
{
    NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
    NSDictionary *params = @{@"msgClientId" : [MsgEngine geMessageClientID],@"AddressBookVersion":addVersion?addVersion:@"0",@"USER_PASSWORD":[self userPassword],@"appVersion":APPVERSION};
    
    [DE serverCall:@"checkIn" params:params callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
        
        NSLog(@"checkin callback =%@    =%hhd",data ,[[NSThread currentThread] isMainThread]);
        
        if(success){
            BOOL canConnectMqtt = YES;
            //验证通过
            if(data && [data objectForKey:@"result"])
            {
                // 优先更新通讯录
                NSDictionary* txl = [data objectForKey:@"txl"];
                if (txl!=nil) {
                    NSString *txlVersion = [txl objectForKey:@"version"];
                    [DE setGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]] value:txlVersion];
                    NSArray * txlls = [txl objectForKey:@"updates"];
                    [ContactDao updataDBwithSQLiteStatement:txlls];
                    
                }
                // 处理离线消息
                if (data && [data objectForKey:@"msg"]) {
                    NSArray *msglist = [data objectForKey:@"msg"];
                    // 收到就签收掉
                    NSMutableArray *receiptMsgIDs = [[NSMutableArray alloc] init];
                    
                    for(int i = 0; i<[msglist count] ; i++){
                        Message *mesg = nil;
                        @try {
                            if (![MessageDao isExistMessageById:[[msglist objectAtIndex:i] objectForKey:@"id"]]) {

                                mesg = [MessageSessionDao updataDBwithSQLiteStatement:[msglist objectAtIndex:i] ];}
                            
                        }
                        @catch (NSException *exception) {
                            NSLog(@"checkin err=%@",exception);
                        }
                        @finally {
                            if(mesg){
                                [self dealRecvMessage:mesg];
                                [receiptMsgIDs addObject:mesg.mID];
                                // 如果为注销命令，则不再继续签收
                                if([@"login_destory" isEqualToString:[mesg getValue:@"businessId"] ])
                                {
                                    canConnectMqtt = NO;
                                    [self recepitMsg:receiptMsgIDs ];
                                    return;
                                }
                            }
                        }
                    }
                    [self recepitMsg:receiptMsgIDs ];
                    
                    if (canConnectMqtt) {
                        [self.msgEngine reconnect];
                    }

                }
                
                
                // 更新敏感词汇
                NSString *keyVersion = [NSString stringWithFormat:@"%@_%@",DE.userId,@"keyBookVersion"];
                if (![[data objectForKey:@"keywordMaxVersion"] isEqualToString:[DE getGlobalVar:keyVersion]]) {
                    [DE serverCall:@"queryKewordsList" params:[[NSDictionary alloc] init] callback:nil];
                }
                //获取天气信息
                _locService = [[BMKLocationService alloc]init];
                _locService.delegate = self;
                [_locService startUserLocationService];
                _geocodesearch = [[BMKGeoCodeSearch alloc]init];
                _geocodesearch.delegate = self;
 
            }else{
                
                [[NSNotificationCenter defaultCenter] postNotificationName:OTHER_CHANGE_BROADCAST object:@{@"code":@"1",@"desc":@"登录状态已经失效，请重新登录！"}];

            }
 
        }
        
    }];
}


/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
/**
 *	@brief	<#Description#>
 *
 *	@param 	userLocation 	<#userLocation description#>
 */
//开启定位服务后，代理调用此函数
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    [_locService stopUserLocationService];
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
     reverseGeocodeSearchOption.reverseGeoPoint = userLocation.location.coordinate;
     BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
     if(flag)
     {
         NSLog(@"反geo检索发送成功");
     }
     else
     {
         NSLog(@"反geo检索发送失败");
         [self GetWeatherData:@"长沙"];
     }
}

-(void) GetWeatherData:(NSString *)sCity{
    //默认
    if([sCity isEqualToString:@""])
        sCity=@"长沙";
  
    NSLog(@"城市：%@",sCity);
    NSDictionary *params = @{@"cityName":sCity};
    
    [DE serverCall:@"queryWeather" params:params callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
        NSMutableDictionary *weather = [NSMutableDictionary dictionary];
        if(success)
        {
            if(data )
            {
                [weather addEntriesFromDictionary:[data objectForKey:@"weather"]];
                [weather setObject:sCity forKey:@"city"];
                //天气图片
                [[NSUserDefaults standardUserDefaults] setObject:weather forKey:@"WeatherData"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                //获取数据后，需要重新刷新首页
                [[NSNotificationCenter defaultCenter] postNotificationName:WEATHER_CHANGE_BROADCAST object:nil];
            }
        }
    }];
}

//反检索后回调函数
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    //默认
    NSString * city =@"";
    if (error == 0) {
        
        NSString * showmeg = [NSString stringWithFormat:@"反向地理编码:%f-%f\n%@",result.location.latitude,
                              result.location.longitude, result.addressDetail.city];
        NSLog(@"%@",showmeg);
        city = [NSString stringWithFormat:@"%@",result.addressDetail.city];
        NSLog(@"onGetReverseGeoCodeResult error 城市：%@",city);
    }
    
    ///20150907 如果city为空，则默认为长沙
    if([city isEqualToString:@""])
        city = @"长沙";
    
    [self GetWeatherData:city];
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error:%@", [error localizedDescription]);
    [_locService stopUserLocationService];
    
    [self GetWeatherData:@"长沙"];
}

-(void)dealRecvMessage:(Message *)message
{
    
    if(!message || !message.messageType || ([message isSendMine] && [MESSAGE_TYPE_P2G isEqualToString: message.messageType])){
        return;
    }
    
    if ([MESSAGE_TYPE_CMD isEqualToString:message.messageType])
    {
        NSString *businessId = [message getValue:@"businessId"];
        if ([@"new_version" isEqualToString:businessId]) {
            // 用户没有忽略过新版本 或者忽略的版本号与当前的不一致，则发送出该版本广播
            NSString *versionCode = [message getValue: @"detail"];
            if(![DE getGlobalVar:LOOK_NEWVERSION] || [versionCode isEqualToString:[DE getGlobalVar:LOOK_NEWVERSION]]){
                [self sendMessageToUI:message funcType:@"new_version"];
                return;
            }
        }
        else if ([@"login_destory"isEqualToString:businessId] || [@"login_out"isEqualToString:businessId]) {
            [self sendMessageToUI:message funcType:businessId];
            return;
        }
        
        else if ([@"addGrpMember"isEqualToString:businessId] || [@"exitGrp"isEqualToString:businessId] || [@"createGrp"isEqualToString:businessId] || [@"virtualGrpUpdateNotify"isEqualToString:businessId]|| [@"becomeFriend"isEqualToString:businessId])
        {
            [self getContactFromService];
        }
        else if ([@"updateGrpName"isEqualToString:businessId]){
            
            NSString *detial = [message getValue:@"detail"];
            if (detial) {
                NSArray *session = [detial componentsSeparatedByString:@","];
                
                NSString *temp =[[session objectAtIndex:1] stringByReplacingOccurrencesOfString: [session objectAtIndex:0] withString :DE.userId];
                NSString *sessionId = [NSString stringWithFormat:@"%@_%@",MESSAGE_TYPE_P2G,temp];
                
                NSString *name =[session objectAtIndex:2];
                
                MessageSession *mesSession = [MessageSessionDao queryMsgSessionById:sessionId];
                mesSession.title = name;
                [MessageSessionDao updateMessageSession:mesSession];
                [self getContactFromService:sessionId businessId:businessId];

            }
        }
        else if ([@"endFriendship"isEqualToString:businessId]) {
            
            NSString *detial = [message getValue:@"detail"];
            if (detial) {
                NSString *sessionId =  [NSString stringWithFormat:@"%@_%@",MESSAGE_TYPE_P2P,detial];
                [MessageSessionDao deleteMessageSession:sessionId];
                [self getContactFromService:sessionId businessId:businessId];
            }
        }
        else if ([@"dropGrp"isEqualToString:businessId]) {
            
            NSString *detial = [message getValue:@"detail"];
            if (detial) {
                NSArray *session = [detial componentsSeparatedByString:@","];
                NSString *temp =[[session objectAtIndex:1] stringByReplacingOccurrencesOfString: [session objectAtIndex:0] withString :DE.userId];
                NSString *sessionId = [NSString stringWithFormat:@"%@_%@",MESSAGE_TYPE_P2G,temp];
                [MessageSessionDao deleteMessageSession:sessionId];
                [self getContactFromService:sessionId businessId:businessId];

            }
        }
        else if ([@"notifyAppRefresh"isEqualToString:businessId]) {
            
            //1:重新获取关注A应用信息
            NSLog(@"notifyAppRefresh---------------%@",message);
            NSString *detial = [message getValue:@"detail"];
            NSString *sessionid = [NSString stringWithFormat:@"%@_%@",MESSAGE_TYPE_P2P,detial];
            
            [MessageSessionDao deleteMessageSession:(sessionid)];
            
            
            
            NSDictionary *map = @{@"user_id":DE.userId};
            [DE serverCall:@"queryApps" params:map callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
                
                if(success)
                {
                    [PublicAccountDao updataDBwithSQLiteStatement:[data objectForKey:@"apps"]];
                    //[MessageSessionDao updataDBwithSQLiteStatement:[data objectForKey:@"apps"]];
                    [DE setGlobalVar:LAST_REFRESH_PUBLIC_TIME value:[[NSDate date] stringFromDateDB]];
                    [[NSNotificationCenter defaultCenter] postNotificationName:PUBLIC_ATTENTION_BROADCAST object:nil];
                    
                    //获取应用分类字典表
                    NSArray *appTypesArray = [data objectForKey:@"dict"];

                    [DataDictDao updataDataDictWithType:appTypesArray dicttypeId:@"6"];
                }
            }];
        }
        
    }
    [self sendMessageToUI:message funcType:message.mesSesion_sess_id];


}

-(void)sendMessageToUI:(Message*)message funcType:(NSString*)sessionId{
    
    NSDictionary *castInfo = @{@"messageId":message.mID,@"messageType":message.messageType,@"messageText":message.text,                               @"senderId":message.senderId,@"receiverId":message.receiverId,@"sessionId":sessionId?sessionId:message.mesSesion_sess_id};
    
    // 发给具体的界面去处理展示
    [[NSNotificationCenter defaultCenter] postNotificationName:DE.msgBroadcastName object:castInfo];

}

-(void)getContactFromService{
    [self getContactFromService:nil businessId:nil];
}


-(void)getContactFromService:(NSString *)sessionId businessId:(NSString*)businessId{
    
    NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
    [DE serverCall:@"refreshAdBook" params:@{@"AddressBookVersion":addVersion?addVersion:@"0"} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary*param) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (success)
            {
                [self updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:sessionId businessId:businessId];
            }
        });
        
    }];
}

-(void)updateLocalDBContacts:(NSDictionary*)txls{
    
    [self updateLocalDBContacts:txls sessionId:nil businessId:nil sendout:YES];
}

-(void)updateLocalDBContacts:(NSDictionary*)txls sessionId:(NSString*)sessionId businessId:(NSString*)businesId{
    [self updateLocalDBContacts:txls sessionId:sessionId businessId:businesId sendout:YES];

}

-(void)updateLocalDBContacts:(NSDictionary*)txls sessionId:(NSString*)sessionId businessId:(NSString*)businesId sendout:(BOOL)send{
    
    NSString *version = [txls objectForKey:@"version"];
    NSArray *updates = [txls objectForKey:@"updates"];
    
    if (updates) {
        
        [ContactDao updataDBwithSQLiteStatement:updates clearFisrt:NO];
        [DE setGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]] value:version];
        
        // 发送通讯录解析完成广播
        if (send && [updates count]>0) {
            NSMutableDictionary *castInfo =[[NSMutableDictionary alloc] init];
            if (businesId) {
                [castInfo setObject:businesId forKey:@"businessId"];
            }
            // 只有解散群组和终止好友关系才会在广播里面加入sessonID
            if (sessionId) {
                [castInfo setObject:sessionId forKey:@"sessionID"];
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:CONTACT_CHANGE_BROADCAST object:castInfo];

        }
    }
}


-(void)recepitMsg:(NSArray*)msgIdList
{
    [DE serverCall:@"receipt" params:@{@"MSGS" : msgIdList} callback:nil];
}



-(NSDictionary*)serverCall:(NSString *)cmd params:(NSDictionary *)params callback:(CallbackBlock)callback
{
    return [self.serverEngine serverCall:cmd params:params callback:callback];
}

-(NSDictionary*)serverCall:(NSString*)cmd params:(NSDictionary*)params callback:(CallbackBlock)callback needCache:(BOOL)needCache{
    return [self.serverEngine serverCall:cmd params:params callback:callback needCache:needCache];
}

-(void)removeRequestCache:(NSString *)name params:(NSDictionary *)params
{
    [ServerEngine removeRequestCache:name params:params];
}



-(NSString*)getGlobalVar:(NSString *)key
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    return [userDefaults objectForKey:key];
}

-(void)setGlobalVar:(NSString *)key value:(NSString *)value
{
    if(value==nil || value == [NSNull class])
        return;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:value forKey:key];
    [userDefaults synchronize];
}

-(void)removeGlobalVar:(NSString *)key
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults removeObjectForKey:key];
    [userDefaults synchronize];
}

+(BOOL)checkPath:(NSString*)path
{
    BOOL isDir = NO;
	NSFileManager* fm = [NSFileManager defaultManager];
	BOOL ret = [fm fileExistsAtPath:path isDirectory:&isDir];
	return ret || isDir;
}

+(BOOL)createDir:(NSString*)path
{
    NSFileManager* fm = [NSFileManager defaultManager];
	return [fm createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
}

#pragma mark - recvMessage

-(void)sendMessage:(NSDictionary*)msgMap callback:(CallbackBlock)callback
{

    [self serverCall:@"sendMessage" params:[msgMap objectForKey:@"content"] callback:callback];
    Message* message = [MessageSessionDao updataDBwithSQLiteStatement:msgMap];
    [self sendMessageToUI:message funcType:message.mesSesion_sess_id];

}


 #pragma mark - ServerCallback

-(BOOL)serverCallback:(NSString *)cmd params:(NSDictionary *)params success:(BOOL)success response:(NSDictionary *)response
{
    NSDictionary* data = [response objectForKey:@"data"];
    if ( [cmd isEqualToString:@"loginCheck"] )
    {
        if ( success )
        {
            NSDictionary* userinfo = [data objectForKey:@"userinfo"];
            NSDictionary* txl = [data objectForKey:@"txl"];
            NSArray *appList = [data objectForKey:@"apps"];
            
            [DE setUserId:[userinfo objectForKey:@"userId"]];
            [DE setUserPassword:[userinfo objectForKey:@"pwd"]];
            
            [DE setGlobalVar:LOGIN_USER_REALID value:[params objectForKey:@"USER_NAME"]];

    
        
            if (txl) {
                NSString *txlVersion = [txl objectForKey:@"version"];
                [DE setGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]] value:txlVersion];
                NSArray * txlls = [txl objectForKey:@"updates"];
                [ContactDao updataDBwithSQLiteStatement:txlls];
            }
            
            if(appList){
                [PublicAccountDao updataDBwithSQLiteStatement:appList];
                [DE setGlobalVar:LAST_REFRESH_PUBLIC_TIME value:[[NSDate date] stringFromDateDB]];

            }
            
            //获取字典表
            NSArray *dataDict = [data objectForKey:@"dict"];
            if (dataDict)
            {
                [DataDictDao updataDBwithSQLiteStatement:dataDict];
            }
            
            
        }
    }
    else if([cmd isEqualToString:@"queryKewordsList"]){
        NSString *servrewordsVesion = [data objectForKey:@"keywordMaxVersion"];
        NSString *kwords = [[data objectForKey:@"list"] JSONString];
        NSString *storeId = [NSString stringWithFormat:@"%@_%@",DE.userId,@"keyBookVersion"];
        [KeyWordDao updateKeyBooks:storeId word:[ServerEngine encryptDES:kwords key:@"12345678"]];
        [DE setGlobalVar:storeId value:servrewordsVesion];
     }
    return YES;
}

#pragma mark - propertys

-(id<DEDelegate>)delegate
{
    return _delegate;
}

-(void)setDelegate:(id<DEDelegate>)delegate
{
    _delegate = delegate;
}

-(ServerEngine*)serverEngine
{
    if ( !_serverEngine )
    {
        _serverEngine = [[ServerEngine alloc] init];
    }
    return _serverEngine;
}

-(MsgEngine*)msgEngine
{
    if ( !_msgEngine )
    {
        _msgEngine = [[MsgEngine alloc] init];
    }
    return _msgEngine;
}

-(NSString*)appId
{
    return _appId;
}

-(void)setAppId:(NSString *)appId
{
    _appId = appId;
}

-(NSString*)fileEngineeUrl
{
    return _fileEngineeUrl;
}

-(void)setFileEngineeUrl:(NSString *)_fileEngineeUrll
{
    _fileEngineeUrl = _fileEngineeUrll;
}


-(NSString*)deviceToken
{
    return _deviceToken;
}

-(void)setDeviceToken:(NSString *)deviceToken
{
    _deviceToken = deviceToken;
}

-(NSString*)terminalId
{
    
    return [[UIDevice currentDevice] uniqueGlobalDeviceIdentifier];

    
    NSUserDefaults *standardUserDefault = [NSUserDefaults standardUserDefaults];
    NSString *deviceIdString = [standardUserDefault objectForKey:@"deviceId"];
    
    if (!deviceIdString || [@"" isEqualToString:deviceIdString]) {
        CFUUIDRef deviceId = CFUUIDCreate (NULL);
        CFRelease(deviceId);
        [standardUserDefault setValue:deviceIdString forKey:@"deviceId"];
        [standardUserDefault synchronize];
    }
    
    return deviceIdString;
    
}

-(NSString*)terminalName
{
    return @"iOS";
}


-(NSString *)osName{

    struct utsname systemInfo;
    uname(&systemInfo);

    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 2G";
    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([deviceString isEqualToString:@"iPhone3,1"] || [deviceString isEqualToString:@"iPhone3,2"] || [deviceString isEqualToString:@"iPhone3,3"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,1"] || [deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,3"] || [deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5c";
    if ([deviceString isEqualToString:@"iPhone6,1"] || [deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5s";
    
    if ([deviceString isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([deviceString isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([deviceString isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([deviceString isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([deviceString isEqualToString:@"iPod5,1"])      return @"iPod Touch 5G";
    
    if ([deviceString isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([deviceString isEqualToString:@"iPad2,1"] || [deviceString isEqualToString:@"iPad2,2"] || [deviceString isEqualToString:@"iPad2,3"] || [deviceString isEqualToString:@"iPad2,4"])      return @"iPad 2";
    if ([deviceString isEqualToString:@"iPad3,1"] || [deviceString isEqualToString:@"iPad3,2"] || [deviceString isEqualToString:@"iPad3,3"])      return @"iPad 3";
    if ([deviceString isEqualToString:@"iPad3,4"] || [deviceString isEqualToString:@"iPad3,5"] || [deviceString isEqualToString:@"iPad3,6"])      return @"iPad 4";
    if ([deviceString isEqualToString:@"iPad4,1"] || [deviceString isEqualToString:@"iPad4,2"])      return @"iPad Air";
    if ([deviceString isEqualToString:@"iPad2,5"] || [deviceString isEqualToString:@"iPad2,6"] || [deviceString isEqualToString:@"iPad2,7"] || [deviceString isEqualToString:@"iPad4,4"] || [deviceString isEqualToString:@"iPad4,5"])      return @"iPad mini";
    

    if ([deviceString isEqualToString:@"i386"])         return @"Simulator";
    if ([deviceString isEqualToString:@"x86_64"])       return @"Simulator";
    
    NSLog(@"NOTE: Unknown device type: %@", deviceString);
    return deviceString;
    
}

-(NSString *)osVersion{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
    
    return app_build;
}

-(NSString*)serverName
{
    return self.serverEngine.serverName;
}

-(void)setServerName:(NSString *)serverName
{
    self.serverEngine.serverName = serverName;
}

-(NSString*)serverProjectName
{
    return self.serverEngine.serverProjectName;
}

-(void)setServerProjectName:(NSString *)serverProjectName
{
    self.serverEngine.serverProjectName = serverProjectName;
}

-(NSString*)serverPort
{
    return self.serverEngine.serverPort;
}

-(void)setServerPort:(NSString *)serverPort
{
    self.serverEngine.serverPort = serverPort;
}

-(NSString*)serverUri
{
    return self.serverEngine.serverUri;
}

-(void)setServerUri:(NSString *)serverUri
{
    self.serverEngine.serverUri = serverUri;
}

-(NSString*)msgServerName
{
    return self.msgEngine.msgServerName;
}

-(void)setMsgServerName:(NSString *)msgServerName
{
    self.msgEngine.msgServerName = msgServerName;
}

-(NSString*)msgServerPort
{
    return self.msgEngine.msgServerPort;
}

-(void)setMsgServerPort:(NSString *)msgServerPort
{
    self.msgEngine.msgServerPort = msgServerPort;
}

-(NSString*)userId
{
    if ( !_userId )
    {
        _userId = [self getGlobalVar:@"userId"];
        if ( !_userId )
            _userId = @"";
     }
    return _userId;
}

-(void)setUserId:(NSString *)userId
{
    _userId = userId;
    [self setGlobalVar:@"userId" value:userId];
    _isLoaded = NO;
}

-(NSString*)userPassword
{
    if ( !_userPassword )
    {
        _userPassword = [self getGlobalVar:@"userPassword"];
        if ( !_userPassword )
            _userPassword = @"";
     }
    return _userPassword;
}

-(void)setUserPassword:(NSString *)userPassword
{
    _userPassword = userPassword;
    [self setGlobalVar:@"userPassword" value:userPassword];
}

-(NSString*)appPath
{
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [NSString stringWithFormat:@"%@/",[paths objectAtIndex:0]];
}

-(NSString*)mainPath
{
    //NSLog(@"%@  ",self.appPath);
    NSString* path = [NSString stringWithFormat:@"%@%@/",self.appPath,self.userId];
    if ( ![DataEngine checkPath:path] )
    {
        [DataEngine createDir:path];
    }
    return path;
}

-(NSString*)dataPath
{
    NSString* path = [NSString stringWithFormat:@"%@%@/",self.mainPath,@"data"];
    if ( ![DataEngine checkPath:path] )
    {
        [DataEngine createDir:path];
    }
    return path;
}

-(NSString*)cachePath
{
    NSString* path = [NSString stringWithFormat:@"%@%@/",self.mainPath,@"cache"];
    if ( ![DataEngine checkPath:path] )
    {
        [DataEngine createDir:path];
    }
    return path;
}




@end


